// pages/shop-cart/shop-cart.js
import {receivingType} from '../../utils/const'
import WxValidate from '../../utils/wxValidate'

const app = getApp()

const {globalData} = app

// 验证字段的规则
const rules = {
  concat_name: {
    required: true,
  },
  concat_phone: {
    required: true,
    tel: true,
  }
}

// 验证字段的提示信息，若不传则调用默认的信息
const messages = {
  receiver_name: {
    required: '请填写联系人',
  },
  receiver_phone: {
    required: '请填写联系电话',
    tel: '联系电话格式不正确',
  }
}

// 抵扣券验证
const deductionRules = {
  deduction_code: {
    required: true,
  },
  deduction_pwd: {
    required: true,
  }
}

// 抵扣券验证字段的提示信息，若不传则调用默认的信息
const deductionMessages = {
  deduction_code: {
    required: '请填写编号',
  },
  deduction_pwd: {
    required: '请输入密码'
  }
}


Component({
  behaviors: [],
  options: {
    pureDataPattern: /^_/, // 指定所有 _ 开头的数据字段为纯数据字段
  },
  properties: {
  },
  /**
   * 页面的初始数据
   */
  data: {
    productList: [],
    totalPrice: 0, // 商品金额
    payPrice: 0, // 支付金额
    receivingType,
    deliverMethod: receivingType.self,
    payMethod: 'weixin', // weixin, cod
    // 自提信息
    selfData: {
      concat_name: '',
      concat_phone: ''
    },
    // 配送地址信息
    address: {
      receiver_name: '',
      receiver_phone: '',
      receiver_province: '',
      receiver_city: '',
      receiver_area: '',
      receiver_address: ''
    },
    errorMessage: {
      receiver_name: '',
      receiver_phone: ''
    },
    duErrorMessage: {
      deduction_code: '',
      deduction_pwd: ''
    },
    // 订单备注
    order_memo: '',
    // 能否使用抵扣券
    isDeduction: false,
    deduction_code: '', // 抵扣券编号
    deduction_pwd: '', // 抵扣券密码
    // 抵扣券信息
    deductionInfo: {
      deduction_code: '',
      deduction_pwd: '',
      deduction_money: 0,
    },
    showSheet: false, // 地址选择弹框
    addressList: [], // 地址列表
    show: false, // 显示抵扣券弹窗
  },
  methods: {
    // tab切换
    tabChangeHandle(event) {
      const {type} = event.currentTarget.dataset
      this.setData({
        deliverMethod: type
      })
    },
    // 地址点击显示 地址选择sheet
    addressTapHandle() {
      this.setData({
        showSheet: true
      })
    },
    sheetCloseHandle() {
      this.setData({
        showSheet: false
      })
    },
    // 支付方式 改变
    payMethodChange(event) {
      const {type} = event.currentTarget.dataset
      this.setData({
        payMethod: type
      })
    },
    // 字段值改变
    fieldChangeHandle(event) {
      const {name} = event.currentTarget.dataset
      const value = event.detail
      this.setData({
        [`selfData.${name}`]: value
      })
    },
    // 输入框失去焦点
    blurHandle(event) {
      const {name} = event.currentTarget.dataset
      const value = this.data.selfData[name]
      this.setData({
        [`errorMessage.${name}`]: this.wxValidate.validateField(name, value)
      })
    },
    // 字段值改变
    duFieldChangeHandle(event) {
      const {name} = event.currentTarget.dataset
      const value = event.detail
      this.setData({
        [`${name}`]: value
      })
    },
    // 输入框失去焦点
    duBlurHandle(event) {
      const {name} = event.currentTarget.dataset
      const value = this.data[name]
      this.setData({
        [`duErrorMessage.${name}`]: this.deductionValidate.validateField(name, value)
      })
    },
    // 订单备注change
    memoChangeHandle(event) {
      this.setData({
        order_memo: event.detail
      })
    },
    buyHandle() {
      let {deliverMethod, productList, selfData, address, order_memo, deductionInfo} = this.data,
        orderInfo = {
          deliverMethod,
          productList: JSON.stringify(productList.map(item => {
            return {
              specs_id: item.specs_id,
              merchant_id: item.merchant_id,
              product_count: item.product_count,
              product_id: item.product_id
            }
          })),
          order_memo
        };
      
      if(deliverMethod == receivingType.self) {
        // 传入表单数据，调用验证方法
        if (!this.wxValidate.checkForm(selfData)) {
          let errorMessage = {}

          this.wxValidate.errorList.forEach(item => {
            errorMessage[item.param] = item.msg
          })
          this.setData({errorMessage})
          return
        }

        orderInfo.concat_name = selfData.concat_name
        orderInfo.concat_phone = selfData.concat_phone
      } else {
        if (!address.receiver_name) {
          wx.showToast({
            title: '请添加地址',
            icon: 'none'
          })
          return
        }
        orderInfo.concat_name = address.receiver_name
        orderInfo.concat_phone = address.receiver_phone
        orderInfo.concat_address = address.receiver_province + ' ' + address.receiver_city + ' ' + address.receiver_area + ' ' + address.receiver_address
      }

      if (deductionInfo.deduction_code) {
        orderInfo.deduction_code = deductionInfo.deduction_code
        orderInfo.deduction_pwd = deductionInfo.deduction_pwd
      }
      orderInfo.shareUserId = this.shareUserId || ''
      this.requestCreateOrder(orderInfo)
    },
    showDialogHandle() {
      this.setData({
        show: true,
        deduction_code: '',
        deduction_pwd: '',
        'duErrorMessage.deduction_code': '',
        'duErrorMessage.deduction_pwd': '',
      }, () => {
        if (!this.myComponent) {
          this.myComponent = this.selectComponent('#van-dialog')
          this.myComponent.onConfirm = () => {
            this.confirmHandle()
          }
        }
      })
    },
    confirmHandle() {
      const {deduction_code, deduction_pwd} = this.data
      const product_info_id=this.data.productList[0].product_id
      const postData = {deduction_code, deduction_pwd,product_info_id}
      if (!this.deductionValidate.checkForm(postData)) {
        let duErrorMessage = {}
        this.deductionValidate.errorList.forEach(item => {
          duErrorMessage[item.param] = item.msg
        })
        this.setData({duErrorMessage})
        return
      }
      this.requestDeductionInfo(postData)
    },
    // 请求优惠券信息
    requestDeductionInfo(postData) {
      wx.ajax.post('queryDeducitonVolume.action', postData, true).then(res => {
        let {min_order_money, deduction_money} = res.result || {}
        let {totalPrice} = this.data
        let payPrice = totalPrice - deduction_money
        if ( totalPrice < min_order_money) {
          return wx.showToast({
            title: '不能使用该优惠券',
            icon: 'none'
          })
        }
        payPrice = payPrice < 0 ? 0 : payPrice
        this.setData({
          show: false,
          payPrice: parseInt(payPrice),
          deductionInfo: {
            ...res.result,
            ...postData,
            deduction_money: deduction_money > totalPrice ? totalPrice : deduction_money
          }
        })
      })
    },
    // 请求接口计算价格
    requestCartSettlement(productList) {
      wx.ajax.post('cartSettlement.action', {productList: JSON.stringify(productList)}, true).then(({result}) => {
        const {totalMoney = 0, productList = [], use_dv} = result
        this.setData({
          isDeduction: use_dv == 1,
          totalPrice: totalMoney,
          payPrice: totalMoney,
          productList: productList.map(item => {
            // item.name = `${item.product_name}(${item.specs_name})`
            item.specs_image = globalData.imageUrl + item.specs_image
            return item
          })
        })
      })
    },
    // 请求默认地址
    requestDefaultAddress() {
      wx.ajax.post('queryDefaultAddress.action').then(({result}) => {
        this.setData({
          address: result || {}
        })
      })
    },
    // 下单
    requestCreateOrder(data) {
      wx.ajax.post('createProductOrder.action', data, true).then(({result}) => {
        const {create_time, order_money, wxPayParam} = result
        if (order_money == 0) {
          wx.navigateTo({
            url: `/pages/pay-result/pay-result?result=1&order_money=${order_money}&create_time=${create_time}`,
          })
        } else {
          wx.requestPayment({
            timeStamp: wxPayParam.timeStamp,
            nonceStr: wxPayParam.nonceStr,
            package: wxPayParam.packageStr,
            signType: wxPayParam.signType,
            paySign: wxPayParam.sign,
            success: () => {
              app.requestShopCart()
              wx.navigateTo({
                url: `/pages/pay-result/pay-result?result=1&order_money=${order_money}&create_time=${create_time}`,
              })
            },
            fail: () => {
              wx.navigateTo({
                url: `/pages/pay-result/pay-result?result=0&order_money=${order_money}&create_time=${create_time}`,
              })
            }
          })
        }
      }).catch(() => {
        // wx.showToast({
        //   title: '',
        // })
      })
    },
    onLoad(options) {
      let {productList, shareUserId} = options
      let userInfo = globalData.userInfo || {}
      
      this.shareUserId = shareUserId
      this.setData({
        "selfData.concat_name": userInfo.name || "",
        "selfData.concat_phone": userInfo.phone || "",
      })

      productList = productList ? JSON.parse(decodeURIComponent(productList)) : []
      this.requestCartSettlement(productList)
      this.requestDefaultAddress()

      this.wxValidate = new WxValidate(rules, messages)

      this.deductionValidate = new WxValidate(deductionRules, deductionMessages)

      wx.hideShareMenu();
    },
    onShow() {
      
    }
  }
})